<%@page contentType="text/html; charset=UTF-8" session="false" %>
<%@include  file="/WEB-INF/jspf/import.jspf"%>
<style>
    #promotionDetailDiv span.error {
        width:200px;
    }
    #promotionDetailDiv .pageFormContent p {
        width:auto;
        line-height: 21px;
        padding: 0;
        margin: 0 0 10px 10px;
    }
</style>
<div id="promotionDetailDiv" class="pageContent">
    <form method="post" action="${ROOT}/admin/promotion/${method }.do" 
          class="pageForm required-validate" onsubmit="return checkForm(this, navTabAjaxDone);">
        <div class="pageFormContent"  layoutH="56">
            <input type="hidden"  name="promotionId" value="${promotion.promotionId}"/>
            <div class="unit">
                <strong>优惠活动</strong>
            </div>
            <div class="divider"></div>
            <div class="unit"> 
                <label>活动图片：</label>
                <input type="hidden" id="logoPic" name="logo" value="${promotion.logo}" class="required"/>
                <a class="button"  href="${ROOT}/admin/promotion/upload.do?command=53023&picSource=logoPic&perShow=perShow&showHref=showPicSrc" width="400" height="250"  target="dialog" maxable="false" resizable="false" rel="upload"><span>上传图片</span></a>
                <a href="${ROOT}/admin/system/showPic.jsp?pic=${promotion.logo}" target="dialog" width="300" height="250" id="showPicSrc">
                    <span id="perShow"><c:if test="${!empty promotion.logo}"><img src="${promotion.logo}" width="63" height="48"></c:if></span></a>
            </div>
            <div class="unit">
                <label>标题：</label>
                <input type="text" value="${promotion.name}" size="50" name="name" class="required">
            </div>
            <div class="unit">
                <label>URL：</label>
                <input type="text" value="${promotion.url}" size="50" id="url" name="url" class="required" onblur="setDateAndSingUpCount();">
            </div>
            
            <div id="themeDate" class="unit">
                 <label>时间：</label>
                 <input class="date" readonly="readonly" id="startDate" name="startDate" size="21" value="<fmt:formatDate value="${promotion.startDate}" pattern="yyyy-MM-dd"/>"/>
                 <span>至</span>
                 <input class="date" readonly="readonly" id="endDate" name="endDate" size="21" value="<fmt:formatDate value="${promotion.endDate}" pattern="yyyy-MM-dd"/>"/>
            </div>
            
            <div id="activityDate" class="unit" hidden="hidden">
                 <label>时间：</label>
                 <input type="text" readonly="readonly" size="50" id="activityDateValue"/>
            </div>
            
            <div id="themeMembers" class="unit">
            	<label>人数限制：</label> 
            		<input type="checkbox" id="unLimit"
						<c:if test="${promotion.signUpCount == 0}">checked="checked"</c:if>
						onchange="setSignUpCount();">无限制 
					<input type="text"
						value="${promotion.signUpCount }" size="20" name="signUpCount"
						id="signUpCount"
						<c:if test="${promotion.signUpCount == 0}">readonly="readonly"</c:if>>
			</div>
            
            <div id="activityMembers" class="unit" hidden="hidden">
            	<label>已报名：</label>
            	<input type="text" readonly="readonly" size="50" id="activityMembersValue">
            </div>

            <div class="unit">
                <label>权重：</label>
                <input type="text" value="${promotion.sortWeight}" size="50" max="99999999" name="sortWeight" class="required digits" min="1">
            </div>
            <div class="unit">
                <strong>推广设置</strong>
            </div>
            <div class="divider"></div>
            <div class="unit"> 
                <label>发送品牌：</label>
                <select id="brandId" name="brandId"><option value="">请选择品牌</option></select>
                <select name="seriesId" id="seriesId" >
                    <option value="">请选择车系(可不选)</option>
                </select>

            </div>
            <div class="unit"> 
                <label>发送地区：</label>
                <select  name="cityId"  id="cityId" ><option value="" selected>-选择地区-</option></select>
                <label style="width:20px">&nbsp;</label>
                <span><a class="button" href="javascript:_addProvinceAndBrand();"><span>添加</span></a></span> 
            </div>
            <!-- 动态生成部分 -->
            <div id="BrandAndProvincePlace" class="unit">
                <label>已选地区品牌：</label>
                <c:forEach items="${privinceBrandList}" var="item" varStatus="st">
                    <div id="BP${st.count}">
                        <p id="brandP">
                            <input type='hidden' name='provinceIds'  value='${item.provinceId}'>
                            <input type='hidden' name='cityIds'  value='${item.cityId}'>
                            <input type='hidden' name='brandIds'  value='${item.brandId}'>
                            <input type='hidden' name='serialsIds'  value='${item.seriesId}'>
                            <input type='hidden' name='provinceNames'  value='${item.provinceName}'>
                            <input type='hidden' name='cityNames'  value='${item.cityName}'>
                            <input type='hidden' name='brandNames'  value='${item.brandName}'>
                            <input type='hidden' name='seriesNames'  value='${item.seriesName}'>${item.name}   
                        </p>
                        <p><a class='button' href='javascript:delAddBP("${st.count}");'><span>删除</span></a></p>
                    </div>
                </c:forEach>
            </div>
            <div class="unit"> 
                <label>发送主题：</label>
                <select class="textInput" id="themeId" name="themeId" >
                    <option value="">请选择</option>
                    <c:forEach items="${themes}" var="theme">
                        <option value="${theme.themeId}" >${theme.themeName}</option>
                    </c:forEach>
                </select>
                <label style="width:20px">&nbsp;</label>
                <span><a class="button" href="javascript:_addTheme();"><span>添加</span></a></span> 
            </div>
            <!-- 动态生成部分 -->
            <div id="addThemePlace" class="unit">
                <label>已选主题：</label>
                <c:forEach items="${themeList}" var="item" varStatus="st">
                    <div id='theme${st.count}'><p id ="themeP">
                            <input type='hidden' name='themeIds'  value='${item.themeId}'>
                            ${item.themeName }</p>
                        <p><a class='button' href='javascript:delTheme("${st.count}","${item.themeId}");'><span>删除</span></a></p>
                    </div>	
                </c:forEach>
            </div>
            <div class="unit"> 
                <label>指定车友会：</label>
                <input type="hidden" name="clubId" id="clubId" value=""/>
                <input type="text" readonly="readonly" id="clubName" name="clubName"  value="${param.clubName}" onchange="loadContractInfo(this)" suggestFields="clubId,clubName"  lookupGroup=""  autocomplete="off"/>
                <a class="btnLook" href="${ROOT}/admin/promotion/club/list.do" lookupGroup="">查找车友会</a>
                <label style="width:20px">&nbsp;</label>
                <span><a class="button" href="javascript:_addClub();"><span>添加</span></a></span> 	
            </div>
            <!-- 动态生成部分 -->
            <div id="addClubPlace" class="unit"> 	
                <label>已选车友会：</label>
                <c:forEach items="${clubList}" var="item" varStatus="st">
                    <div id='club${st.count}'><p id="clubP">
                            <input type='hidden' name='clubIds'  value='${item.clubId }'>
                            ${item.clubName }</p>
                        <p><a class='button' href='javascript:delClub("${st.count}","${item.clubId }");'><span>删除</span></a></p>
                    </div>	
                </c:forEach>      
            </div>
            <div class="unit"> 
                <label>开始时间：</label>
                <input class="date required" readonly="readonly" id="push_startDate" name="push_startDate" value="<fmt:formatDate value="${promotion.promotionPublish.startDate}" pattern="yyyy-MM-dd"/>"/>
            </div>
            <div class="unit"> 
                <label>结束时间：</label>
                <input class="date required" readonly="readonly" id="push_endDate" name="push_endDate" value="<fmt:formatDate value="${promotion.promotionPublish.endDate}" pattern="yyyy-MM-dd"/>"/>
            </div>

        </div>
        <div class="formBar">
            <ul>
                <li><div class="buttonActive"><div class="buttonContent"><button type="submit">保存</button></div></div></li>
                <li><div class="button"><div class="buttonContent"><button class="close" type="button">关闭</button></div></div></li>
            </ul>
        </div>

    </form>
</div>
<script>
	//是否无限制报名人数，相应动作
	function setSignUpCount() {
		if($("#unLimit").attr("checked")){
			$("#signUpCount").attr("readonly","readonly");
		} else {
			$("#signUpCount").removeAttr("readonly");
		}
	}
	
	//如果是活动帖子，获取论坛中的活动有效时间，和已报名人数
	function setDateAndSingUpCount() {
		var urlStr = $("#url").val();
		var topicId = 0;
		//判断是为论坛中的帖子   
		var beginBbs = urlStr.indexOf("bbs.pcauto.com.cn/");
		//找不到匹配，即为主题URL
		if(beginBbs == -1) {
			//隐藏活动相关信息
	    	$("#activityDate").hide();
	    	$("#activityMembers").hide();
			//显示主题相关信息
	    	$("#themeDate").show();
	    	$("#themeMembers").show();
		} else {//找到匹配，即为活动URL
			var beginTopicId = urlStr.indexOf("topic-");
		    var endTopicId = urlStr.indexOf(".html");
		    topicId = urlStr.substring(beginTopicId + "topic-".length , endTopicId);
		    
		    if(topicId != '0') {
		    	var url = "${BBSROOT}/intf/activity/read.do?tid="+topicId;
		    	$.ajax({
	                type:"get",
	                dataType : "jsonp",
	                url:url,
	                success:function(data){
	                    if(data.status==0){
	                    	//隐藏主题相关信息
	                    	$("#themeDate").hide();
	                    	$("#themeMembers").hide();
	                    	//显示活动相关信息
	                    	$("#activityDate").show();
	                    	$("#activityMembers").show();
	                    	$("#activityDateValue").attr("value", data.createAtMin + "-" + data.createAtMax);
	                    	$("#activityMembersValue").attr("value", data.signUpCount);
	                    }else{
	                    	//隐藏活动相关信息
	            	    	$("#activityDate").hide();
	            	    	$("#activityMembers").hide();
	            			//显示主题相关信息
	            	    	$("#themeDate").show();
	            	    	$("#themeMembers").show();
	                        console.log("error "+topicId+" "+data.desc);
	                    }
	                },
	                error:function(){
	                	console.log("fail to get activity info, topicId "+topicId);
	                }
	            });
		    	
		    };
		};
	}
	setDateAndSingUpCount();
	
    //车友会地区
    $.getScript("${UCROOT}/intf/area.jsp?tag=cityId&selected=0&defaultCityTips=1");
    jQuery.getScript("${ROOT}/js/brand_series.js",function(){
        //车系
        relatedSelect(
        {id:"brandId",url:"http://price.pcauto.com.cn/interface/5_3/brand_json_chooser_v2.jsp?_t=" + new Date().getTime(),node:{root:"brands", value:"id", text:"text",custom:"id"},load:true<c:if test="${club.brandId>0}">,defaultValue:${club.brandId}</c:if>},
        {id:"seriesId",url:"http://price.pcauto.com.cn/interface/5_3/serial_json_chooser.jsp?brand=",node:{root:"firms", value:"id", text:"text",custom:"id"}<c:if test="${club.seriesId>0}">,defaultValue:${club.seriesId}</c:if>});
    
        $("#brandId").change(function(){
            var selectText = $(this).find("option:selected").text();
            $("#brandName").val(selectText); 
            //选完品牌要清车系
            $("#seriesName").val("");
        });
        $("#seriesId").change(function(){
            var selectText = $(this).find("option:selected").text();
            $("#seriesName").val(selectText); 
        });
    });
    function checkForm(frm, navTabAjaxDone){
        var start = $("#push_startDate").val().replace(/-/g,"/");
        var end = $("#push_endDate").val().replace(/-/g,"/");
        var startDate = new Date(start);
        var endDate = new Date(end);
        if(startDate>endDate){
            alertMsg.warn("优惠开始时间大于优惠结束时间");
            return false;
        }
        
        var actStart = $("#startDate").val().replace(/-/g,"/");
        var actEnd = $("#endDate").val().replace(/-/g,"/");
        var actStartDate = new Date(actStart);
        var actEndDate = new Date(actEnd);
        if(actStartDate>actEndDate){
            alertMsg.warn("活动开始时间大于活动结束时间");
            return false;
        }
        
     	//选择无限制报名人数，设置报名人数=0
     	if($("#unLimit").attr("checked")) {
     		$("#signUpCount").val(0);
     	} 
    	
        if (!validateCallback(frm, navTabAjaxDone)) {
            return false;
        }else{
            return true;
        }
    }

    //添加品牌+地区
    var BPLength = ${fn:length(privinceBrandList)};
    var index = BPLength+1;
    var selectArr = new Array();
    $("p[id='brandP']").each(function(i,obj){
        var provinceId =$("input[name='provinceIds']",obj).val();
        var cityId =$("input[name='cityIds']",obj).val();
        var brandId =$("input[name='brandIds']",obj).val();
        var seriesId =$("input[name='serialsIds']",obj).val();
        var selctObj = new Object();
        selctObj.index = i+1;
        selctObj.provinceId = provinceId;
        selctObj.cityId = cityId;
        selctObj.brandId = brandId;
        selctObj.seriesId = seriesId;
        selectArr.push(selctObj);
    });


    function _addProvinceAndBrand(){
        var provinceOption = $("#areaParentTag_cityId").find("option:selected");
        var cityOption = $("#cityId").find("option:selected");
        var brandIdOption = $("#brandId").find("option:selected");
        var seriesIdOption = $("#seriesId").find("option:selected");
        if(provinceOption.val()==''&&brandIdOption.val()==''){
            alertMsg.warn("没有选择任何条件添加");
            return;
        }
        var provinceName = provinceOption.text();
        var provinceId = provinceOption.val();
        var cityName = cityOption.text().replace("├","");
        var cityId = cityOption.val();
        var brandName = brandIdOption.text();
        var brandId = brandIdOption.val();
        var seriesName = seriesIdOption.text();
        var seriesId = seriesIdOption.val();
        if(provinceId==""){
            provinceId= 0;
            provinceName="";
        }
        if(cityId==""){
            cityId=0;
            cityName="";
        }
        if(brandId==""){
            brandId=0;
            brandName="";
        }
        if(seriesId==""){
            seriesId=0;
            seriesName="";
        }
	 
        if(checkSelect(provinceId,cityId,brandId,seriesId)){
            alertMsg.warn("已添加该条件");
            return;
        }
	
        var addText = "";
        if(cityId!=""){
            addText +=cityName.replace("├","");
        }else if(provinceId!=""){
            addText +=provinceName;
        }
        if(seriesId!=""){
            addText +=seriesName;
        }else if(brandId!=""){
            addText +=brandName;
        }
        var html = "<div id='BP"+index+"'><p>"+
            "<input type='hidden' name='provinceNames' id='provinceName"+index+"' value='"+provinceName+"'>"+
            "<input type='hidden' name='cityNames' id='cityName"+index+"' value='"+cityName+"'>"+
            "<input type='hidden' name='brandNames' id='brandName"+index+"' value='"+brandName+"'>"+
            "<input type='hidden' name='seriesNames' id='seriesName"+index+"' value='"+seriesName+"'>"+
            "<input type='hidden' name='provinceIds' id='provinceId"+index+"' value='"+provinceId+"'>"+
            "<input type='hidden' name='cityIds' id='cityId"+index+"' value='"+cityId+"'>"+
            "<input type='hidden' name='brandIds' id='brandId"+index+"' value='"+brandId+"'>"+
            "<input type='hidden' name='serialsIds' id='serialsId"+index+"' value='"+seriesId+"'>"+
            ""+addText+"</p>"+
            "<p><a class='button' href='javascript:delAddBP(\""+index+"\");'><span>删除</span></a></p>"+
            "</div>";
        $("#BrandAndProvincePlace").append(html);
        var selctObj = new Object();
        selctObj.index = index;
        selctObj.provinceId = provinceId;
        selctObj.cityId = cityId;
        selctObj.brandId = brandId;
        selctObj.seriesId = seriesId;
        selectArr.push(selctObj);
        index++;
    }
    //判断是否已经添加
    function checkSelect(provinceId,cityId,brandId,seriesId){
        for(var i=0;i<selectArr.length;i++){
            var obj = selectArr[i];
            var arr_provinceId = obj.provinceId;
            var arr_cityId = obj.cityId;
            var arr_brandId = obj.brandId;
            var arr_seriesId = obj.seriesId;
            if(arr_provinceId==provinceId&&arr_cityId==cityId&&arr_brandId==brandId&&arr_seriesId==seriesId){
                return true;
            }
        }
	
        return false;
    }
    //删除（品牌+地区）所选条件方法
    function delAddBP(count){
        for(var i=0;i<selectArr.length;i++){
            var obj = selectArr[i];
            if(obj.index==count){
                selectArr.splice(i,1);
                break;
            }
        }
        $("#BP"+count).remove();
    }
    //添加特定车友会
    var clubLength = ${fn:length(clubList)};
    var clubIndex =clubLength+1;
    var selectClubArr = new Array();
    $("p[id='clubP']").each(function(i,obj){
        var themeId =$("input[name='clubIds']",obj).val();
        selectClubArr.push(themeId);
    });



    function _addClub(){
        var clubId = $("#clubId").val();
        var clubName = $("#clubName").val();
        if(clubId==""||clubName==""){
            alertMsg.warn("没有选择车友会添加");
            return;
        }
        if(checkSelectClub(clubId)){
            alertMsg.warn("已经选择了该车友会");
            return;
        }
        var html = "<div id='club"+clubIndex+"'><p>"+
            "<input type='hidden' name='clubIds' id='clubIds"+clubIndex+"' value='"+clubId+"'>"+
            ""+clubName+"</p>"+
            "<p><a class='button' href='javascript:delClub(\""+clubIndex+"\",\""+clubId+"\");'><span>删除</span></a></p>"+
            "</div>";	
        $("#addClubPlace").append(html);
        selectClubArr.push(clubId);	
        clubIndex++;
    }
    //判断是否已经添加过的车友会
    function checkSelectClub(clubId){
        for(var i=0;i<selectClubArr.length;i++){
            var selectClubId = selectClubArr[i];
            if(selectClubId==clubId){
                return true;
            }
        }
	
        return false;
    }
    //删除添加的车友会
    function delClub(clubCount,clubId){
        for(var i=0;i<selectClubArr.length;i++){
            var selectClubId = selectClubArr[i];
            if(selectClubId==clubId){
                selectClubArr.splice(i,1);
                break;
            }
        }
        $("#club"+clubCount).remove();
    }
    var themeLength = ${fn:length(themeList)};
    var themeIndex =themeLength+1;
    var selectThemeArr = new Array();
    $("p[id='themeP']").each(function(i,obj){
        var themeId =$("input[name='themeIds']",obj).val();
        selectThemeArr.push(themeId);
    });
    //添加主题
    function _addTheme(){
        var themeId = $("#themeId").find("option:selected").val();
        var themeName = $("#themeId").find("option:selected").text();
        if(themeId==""){
            alertMsg.warn("没有选择主题添加");
            return;
        }
        if(checkSelectTheme(themeId)){
            alertMsg.warn("已经添加该主题");
            return;
        }
        var html = "<div id='theme"+themeIndex+"'><p>"+
            "<input type='hidden' name='themeIds' id='themeIds"+themeIndex+"' value='"+themeId+"'>"+
            ""+themeName+"</p>"+
            "<p><a class='button' href='javascript:delTheme(\""+themeIndex+"\",\""+themeId+"\");'><span>删除</span></a></p>"+
            "</div>";		
        $("#addThemePlace").append(html);
        selectThemeArr.push(themeId);
        themeIndex++;
    }
    //判断是否已经添加过的车友会
    function checkSelectTheme(themeId){
        for(var i=0;i<selectThemeArr.length;i++){
            var selectThemeId = selectThemeArr[i];
            if(selectThemeId==themeId){
                return true;
            }
        }
	
        return false;
    }
    //删除添加的主题
    function delTheme(themeCount,themeId){
        for(var i=0;i<selectThemeArr.length;i++){
            var selectThemeId = selectThemeArr[i];
            if(selectThemeId==themeId){
                selectThemeArr.splice(i,1);
                break;
            }
        }
        $("#theme"+themeCount).remove();
    }
</script>